import React, { Suspense } from "react";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { Spin } from "antd";
import { routes } from "./routes";
import type { AppRouteObject } from "./routes";
import AuthGuard from "./AuthGuard";

// 路由加载时的加载组件
const LoadingComponent = () => (
  <div
    style={{
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
      height: "100vh",
    }}
  >
    <Spin size="large" />
  </div>
);

// 处理路由配置，添加路由守卫
const processRoutes = (routes: AppRouteObject[]): AppRouteObject[] => {
  return routes.map((route) => ({
    ...route,
    element: (
      <Suspense fallback={<LoadingComponent />}>
        <AuthGuard route={route}>{route.element}</AuthGuard>
      </Suspense>
    ),
    children: route.children ? processRoutes(route.children) : undefined,
  }));
};

const router = createBrowserRouter(processRoutes(routes));

const Router: React.FC = () => {
  return <RouterProvider router={router} />;
};

export default Router;
